﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace DiscoveryLogic.DataViz.NetworkDiagram.Rules
{
    /// <summary>
    /// 
    /// </summary>
    public class RuleManager
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="rule"></param>
        public static void SaveRule(EntityRelationRule rule)
        {
            XmlDocument xDoc=new XmlDocument();
            xDoc.LoadXml("<EntityRelationRule></EntityRelationRule>");
            XmlNode root = xDoc.DocumentElement;
            rule.Save(ref xDoc, root);

            string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            appFolder = Path.Combine(appFolder, "Network Data");
            if (!Directory.Exists(appFolder))
                Directory.CreateDirectory(appFolder);
            string ruleFilePath = Path.Combine(appFolder, rule.RuleName + ".rule");
            xDoc.Save(ruleFilePath);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public static List<EntityRelationRule> GetAllEntityRelationRules()
        {
            List<EntityRelationRule> rules=new List<EntityRelationRule>();
            string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            appFolder = Path.Combine(appFolder, "Network Data");
            if (!Directory.Exists(appFolder))
                Directory.CreateDirectory(appFolder);
            DirectoryInfo dirInfo=new DirectoryInfo(appFolder);
            FileInfo[] fileInfos = dirInfo.GetFiles("*.rule", SearchOption.TopDirectoryOnly);
            if(fileInfos !=null && fileInfos.Length>0)
            {
                foreach(FileInfo fileInfo in fileInfos)
                {
                    XmlDocument xDoc = new XmlDocument();
                    xDoc.Load(fileInfo.FullName);
                    XmlNode root = xDoc.DocumentElement;
                    if (root.Name == "EntityRelationRule")
                    {
                        EntityRelationRule rule = EntityRelationRule.ReadRelationRule(root);
                        rules.Add(rule);
                    }
                }
            }
            return rules;
        }

        public static void DeleteRule(string ruleName)
        {
            string appFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
            appFolder = Path.Combine(appFolder, "Network Data");
            if (!Directory.Exists(appFolder))
                Directory.CreateDirectory(appFolder);
            string filePath = Path.Combine(appFolder, ruleName + ".rule");
            if(File.Exists(filePath))
                File.Delete(filePath);
        }
    }
}
